package com.sensor.meter.activity

import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import com.sensor.meter.R
import com.sensor.meter.fragment.DialogFra
import com.sensor.meter.utils.AudioRecordUtil
import com.sensor.meter.utils.LogUtil
import com.sensor.meter.widget.SoundMeterView
import java.lang.ref.WeakReference

/**
 * @author       CT
 * @date         2024/3/5
 * @description  分贝仪
 *
 */
class SoundMeter : AppCompatActivity() {

  private var actRltLauncher: ActivityResultLauncher<String>? = null
  private var soundMeterView: SoundMeterView? = null
  private var tvMinValue:AppCompatTextView?=null
  private var tvAverageValue:AppCompatTextView?=null
  private var tvMaxValue:AppCompatTextView?=null
  private var minValue:Int=0
  private var maxValue:Int=0
  private val dataLst= mutableListOf<Int>(0)
  private lateinit var audioRecord: AudioRecordUtil

  private val mHandler = InnerHandler(WeakReference(this))

  private class InnerHandler(val wrfAct: WeakReference<SoundMeter>) : Handler(Looper.getMainLooper()) {
    override fun handleMessage(msg: Message) {
      super.handleMessage(msg)
      wrfAct.get()?.run {
        soundMeterView!!.currentValue = msg.what.toFloat()
        dataLst.add(msg.what)
        if(minValue<=0){
          minValue=msg.what
        }
        if (maxValue<=0){
          maxValue=msg.what
        }
        if(msg.what< minValue ){
          minValue=msg.what
        }else if(msg.what > maxValue){
          maxValue=msg.what
        }
        updateValue()
      }
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_sound_meter)
    setTitle(R.string.title_sound_meter)
    val actionBar = supportActionBar
    actionBar!!.setHomeButtonEnabled(true)
    actionBar!!.setDisplayHomeAsUpEnabled(true)
    soundMeterView = findViewById<SoundMeterView>(R.id.dashboard)
    soundMeterView!!.setClockValueArea(200, 0, "dB")
    tvMinValue=findViewById(R.id.tv_min_value)
    tvAverageValue=findViewById(R.id.tv_average_value)
    tvMaxValue=findViewById(R.id.tv_max_value)
    //
    actRltLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
      if (it) {
        //权限申请通过
        startListening()
      }
    }
    //检查权限
    actRltLauncher!!.launch(Manifest.permission.RECORD_AUDIO)
  }

 private fun updateValue(){
    tvMinValue!!.text= minValue.toString()
    tvAverageValue!!.text=dataLst.average()!!.toInt().toString()
    tvMaxValue!!.text=maxValue.toString()
  }

  private fun startListening() {
    audioRecord = AudioRecordUtil {
      mHandler.sendEmptyMessage(it.toInt())
    }
    audioRecord.start()
  }

  override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    val inflater: MenuInflater = menuInflater
    inflater.inflate(R.menu.options_menu, menu)
    return super.onCreateOptionsMenu(menu)
  }

  override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
      //onBackPressed()
      android.R.id.home -> onBackPressedDispatcher.onBackPressed()
      R.id.action_desc -> showDescFragment()
    }
    return super.onOptionsItemSelected(item)
  }


  private fun showDescFragment(){
    val dialog= DialogFra(R.layout.dialog_sound_meter_desc)
    dialog.showDialogFragment(supportFragmentManager)
  }

  override fun onDestroy() {
    super.onDestroy()
    actRltLauncher!!.unregister()
    audioRecord!!.stop()
  }

}